<?php

namespace App\Services;

use App\Ad\Postback\PostbackService;
use App\Commons\CommonConstant;
use App\Jobs\AdPostbackQueue;
use App\Models\FirstupAd;
use App\Models\Orders;
use App\Models\Users;

class AdPostbackService extends ServiceBase
{
    public function addPostback($convert_type, $firstup_ad, $mod_id)
    {
        $log = PostbackService::getInstance()->addPostback($convert_type, $firstup_ad, $mod_id);
        if (!$log) {
            return;
        }

        AdPostbackQueue::dispatch($log->id)->onQueue('default');
    }

    // 激活匹配成功后进行回传。并将关联的注册和付费一起回传
    public function postbackFirstUp($firstup_ad)
    {
        // 激活回传
        $this->addPostback(CommonConstant::EVENT_FIRSTUP, $firstup_ad, $firstup_ad->firstup_id);

        // 注册回传
        $users = Users::where('firstup_id', $firstup_ad->firstup_id)->get();
        foreach ($users as $val) {
            $this->addPostback(CommonConstant::EVENT_REG, $firstup_ad, $val->user_id);

            // 付费回传
            $orders = Orders::where('user_id', $val->user_id)->whereIn('status', [1,2,3,201])->get();
            foreach ($orders as $order) {
                $this->addPostback(CommonConstant::EVENT_PAY, $firstup_ad, $order->id);
            }
        }
    }

    // 注册成功回传
    public function postbackReg($user)
    {
        if ($user->firstup_id <= 0) {
            return;
        }
        $firstup_ad = FirstupAd::where('firstup_id', $user->firstup_id)->first();
        if (!$firstup_ad || $firstup_ad->monitor_id <= 0) {
            return;
        }

        $this->addPostback(CommonConstant::EVENT_REG, $firstup_ad, $user->user_id);
    }

    // 支付成功回传
    public function postbackPay($order)
    {
        $user = Users::find($order->user_id);
        if ($user->firstup_id <= 0) {
            return;
        }
        $firstup_ad = FirstupAd::where('firstup_id', $user->firstup_id)->first();
        if (!$firstup_ad || $firstup_ad->monitor_id <= 0) {
            // 自然量或者联通时会基于此处数据处理的
            OrdersCallClientService::getInstance()->addCall($order);
            return;
        }

        $this->addPostback(CommonConstant::EVENT_PAY, $firstup_ad, $order->id);
    }
}
